package com.lg.online_shop.controller;

import com.lg.online_shop.enmu.OrderEnum;
import com.lg.online_shop.entity.*;
import com.lg.online_shop.mapper.*;
import com.lg.online_shop.utils.Result;
import com.lg.online_shop.vo.OrderVo;
import jakarta.annotation.Resource;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {

    private static final Logger log = LoggerFactory.getLogger(OrderController.class);
    @Resource
    private OrderMapper orderMapper;

    @Resource
    private SizeMapper sizeMapper;

    @Resource
    private ColorMapper colorMapper;


    @Resource
    private AddressMapper addressMapper;

    @Resource
    private CartMapper cartMapper;

    @Resource
    private GoodMapper goodMapper;


    //    根据用户 id 获取订单
    @GetMapping("/getOrderByUid")
    public Result getOrderByUid(int uId) {
        List<Orders> ordersList = orderMapper.selectOrderByUid(uId);
        List<OrderVo> orderVoList = new ArrayList<>();
//      通过 colorId 和 sizeId 获取颜色和尺码
        for (Orders orders : ordersList) {
//           System.out.println(orders);
            Size size = sizeMapper.selectSizeBySizeId(orders.getSizeId()).get(0);
            Color color = colorMapper.selectColorByColorId(orders.getColorId()).get(0);
            OrderVo orderVo = new OrderVo();
            BeanUtils.copyProperties(orders, orderVo);
            orderVo.setSize(size.getSize());
            orderVo.setColor(color.getColor());
            orderVo.setStatus(OrderEnum.fromCode(orders.getStatus()).getDescription());
            orderVoList.add(orderVo);
        }
        return Result.success(orderVoList);
    }


    //   取消订单
    @GetMapping("/cancelOrder")
    public Result deleteOrder(Long id) {
//        将status改成2
        int i = orderMapper.updateOrderStatus(id, OrderEnum.DELETED.getCode());

        return i > 0 ? Result.success("取消订单成功") : Result.error("取消订单失败");
    }

    //    获取订单详情
    @GetMapping("/getOrderDetail")
    public Result getOrderDetail(int id) {
        Orders orders = orderMapper.selectById(id);

        // 通过 colorId 和 sizeId 获取颜色和尺码
        Size size = sizeMapper.selectSizeBySizeId(orders.getSizeId()).get(0);
        Color color = colorMapper.selectColorByColorId(orders.getColorId()).get(0);
//        根据 id 查询地址
        Address address = addressMapper.selectById(orders.getAddressId());

        OrderVo orderVo = new OrderVo();

        BeanUtils.copyProperties(orders, orderVo);
        orderVo.setSize(size.getSize());
        orderVo.setColor(color.getColor());
        orderVo.setAddressName(address.getAddressName());
        orderVo.setPhone(address.getPhone());
        orderVo.setAddressee(address.getAddressee());

        System.out.println(orderVo);
        try {
            orderVo.setStatus(OrderEnum.fromCode(orders.getStatus()).getDescription());
        } catch (IllegalArgumentException e) {
            System.out.println("未知的订单状态码: " + orders.getStatus());
            orderVo.setStatus("未知状态"); // 设置默认状态以防 null
        }

        return Result.success(orderVo);
    }


    //    支付订单
    @GetMapping("/payOrder")
    public Result payOrder(Long id) {
        int i = orderMapper.updateOrderStatus(id, OrderEnum.PAID.getCode());
        return i > 0 ? Result.success("支付订单成功") : Result.error("支付订单失败");
    }

    //    获取购买历史，即 status 为1 的订单
    @GetMapping("/getBuyHistory")
    public Result getBuyHistory(Long uId) {
        List<Orders> ordersList = orderMapper.selectBuyHistory(uId);
        List<OrderVo> orderVoList = new ArrayList<>();
//      通过 colorId 和 sizeId 获取颜色和尺码
        for (Orders orders : ordersList) {
            Size size = sizeMapper.selectSizeBySizeId(orders.getSizeId()).get(0);
            Color color = colorMapper.selectColorByColorId(orders.getColorId()).get(0);
            OrderVo orderVo = new OrderVo();
            BeanUtils.copyProperties(orders, orderVo);
            orderVo.setSize(size.getSize());
            orderVo.setColor(color.getColor());
            orderVo.setStatus(OrderEnum.fromCode(orders.getStatus()).getDescription());
            orderVoList.add(orderVo);
        }
        return Result.success(orderVoList);
    }


    //    添加订单
    @GetMapping("/addOrder")
    public Result addOrder(Long uId) {
//        获取购物车信息
        List<Cart> cartInfo = cartMapper.selectByUId(uId);
        if (cartInfo.isEmpty()) {
            return Result.error("购物车为空");
        }
        List<Orders> ordersList = new ArrayList<>();
        for (Cart cart : cartInfo) {
//            获取商品信息
            Good good = goodMapper.selectById(cart.getGId());
//            获取库存
            Integer stock = good.getGStock();
//            判断库存是否足够
            if (stock < cart.getCount()) {
                return Result.error("库存不足");
            }
//            更新库存
            good.setGStock(stock - cart.getCount());
            goodMapper.updateById(good);
//            添加订单
            Orders orders = new Orders();
            BeanUtils.copyProperties(cart, orders);
            orders.setGName(good.getGName());
            orders.setStatus(OrderEnum.UNPAID.getCode());
//            计算总价
            orders.setTotalPrice(good.getGPrice() * cart.getCount());
//            获取地址信息
            Address address = addressMapper.selectByUId(uId).get(0);
            orders.setAddressId(address.getId());
            ordersList.add(orders);
        }
        for (Orders orders : ordersList) {
            orderMapper.insertOrder(orders);
        }
//        清空购物车
//        cartMapper.selectByUId(uId).forEach(cart -> cartMapper.deleteById(cart.getId()));
        return Result.success();
    }


//    结账购物车
    @GetMapping("/buyCart")
    public Result buyCart(@Param("uId") Long uId,@Param("addressId") Long addressId)
    {
        List<Cart> cartInfo = cartMapper.selectByUId(uId);
        if (cartInfo.isEmpty())
        {
            return Result.error("购物车为空");
        }
        List<Orders> ordersList = new ArrayList<>();
        for (Cart cart : cartInfo)
        {
            Good good = goodMapper.selectById(cart.getGId());
            Integer stock = good.getGStock();
            if (stock < cart.getCount())
            {
                return Result.error("库存不足");
            }
            good.setGStock(stock - cart.getCount());
            goodMapper.updateById(good);
            Orders orders = new Orders();
            BeanUtils.copyProperties(cart, orders);
            orders.setGName(good.getGName());
            orders.setStatus(OrderEnum.PAID.getCode());
            orders.setTotalPrice(good.getGPrice() * cart.getCount());
            Address address = addressMapper.selectByUId(uId).get(0);
            orders.setAddressId(addressId);
            ordersList.add(orders);
        }
        for (Orders orders : ordersList)
        {
            orderMapper.insertOrder(orders);
        }
        //        清空购物车
        cartMapper.selectByUId(uId).forEach(cart -> cartMapper.deleteById(cart.getId()));
        return Result.success("支付成功");
    }
}
